package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.hmdp.constant.NumConstant;
import com.hmdp.constant.RedisConstant;
import com.hmdp.constant.StatusConstant;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CacheClient cacheClient;

    /**
     * 根據id查詢店家資訊
     *
     * @param id
     * @return
     */
    public Result queryShopById(Long id) {
//        Shop shop = queryWithMutex(id);
//        Shop shop = queryWithLogicalExpire(id);

        Shop shop = cacheClient.queryWithLogicalExpire
                (id, RedisConstant.SHOP_ID, Shop.class, this::getById, NumConstant.SHOP_ID_TTL, TimeUnit.MINUTES);
        if (shop == null) {
            return Result.fail(StatusConstant.SHOP_NOT_EXIST);
        }
        return Result.ok(shop);
    }

    private Shop queryPassThrough(Long id) {
        Shop shop = null;
        String key = RedisConstant.SHOP_ID + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isNotBlank(shopJson)) {
            shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        if (shopJson != null) {
            return null;
        }
        shop = getById(id);
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(key, "", NumConstant.SHOP_ID_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        String shopStr = JSONUtil.toJsonStr(shop);

        stringRedisTemplate.opsForValue().set(key, shopStr, NumConstant.SHOP_ID_TTL, TimeUnit.MINUTES);
        return shop;
    }


    public Shop queryWithMutex(Long id) {
        String key = RedisConstant.SHOP_ID + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }


        if (shopJson != null) {
            return null;
        }

        String lockKey = RedisConstant.SHOP_ID_LOCK + id;

        boolean isLock = tryLock(lockKey);
        Shop shop = null;

        try {
            if (!isLock) {
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            shop = getById(id);
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(key, "", NumConstant.SHOP_ID_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }

            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), NumConstant.SHOP_ID_TTL, TimeUnit.MINUTES);

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            unlock(lockKey);
        }
        return shop;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 利用逻辑过期解决缓存击穿问题
     *
     * @param id
     * @return
     */
    public Shop queryWithLogicalExpire(Long id) {
        String key = RedisConstant.SHOP_ID + id;
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();

        //1.從店鋪查詢店鋪緩存
        String json = opsForValue.get(key);

        //2.判斷是否存在
        if (StrUtil.isBlankIfStr(json)) {
            //3.未命中,返回null
            return null;
        }
        //4.命中
        //4.1.判斷是否已經過期
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();

        //4.2.未過期,返回店鋪信息
        if (expireTime.isAfter(LocalDateTime.now())) {
            return shop;
        }

        //4.3.已過期,嘗試獲取互斥鎖
        String lockKey = RedisConstant.SHOP_ID_LOCK + id;
        boolean isLock = tryLock(lockKey);

        //4.3.1.獲取失敗,返回店鋪信息
        if (!isLock) {
            return shop;
        }

        //4.3.2.獲取成功,開啓獨立綫程,返回店鋪信息
        CACHE_REBUILD_EXECUTOR.submit(() -> {
            try {
                // 4.3.3查詢數據庫,將店鋪數據寫入redis,並設置邏輯過期時間
                this.saveShopToRedis(id, 20L);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 4.3.4釋放互斥鎖
                unlock(lockKey);
            }
        });
        return shop;
    }

    /**
     * 更新
     *
     * @param shop
     * @return
     */
    public Result update(Shop shop) {

        Long id = shop.getId();

        if (id == null) {
            return Result.fail(StatusConstant.SHOP_NOT_EXIST);
        }

        updateById(shop);
        String key = RedisConstant.SHOP_ID + id;
        stringRedisTemplate.delete(key);
        return Result.ok();
    }

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 保存店家資訊到redis
     *
     * @param id
     * @param expireSeconds
     */
    public void saveShopToRedis(Long id, Long expireSeconds) {
        // 查詢店家資訊
        Shop shop = getById(id);

        //封裝邏輯過期時間
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));

        // 存入redis
        stringRedisTemplate.opsForValue().set(RedisConstant.SHOP_ID + id, JSONUtil.toJsonStr(redisData));
    }
}
